package com.lin.lazybone.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.lin.lazybone.ImMessageHandler;
import com.lin.lazybone.R;
import com.lin.lazybone.adapter.MesListAdapter;
import com.lin.lazybone.entity.Message;
import com.lin.lazybone.entity._User;
import com.lin.lazybone.ui.ChatActivity;
import com.lin.lazybone.utils.L;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by mr.lin on 2017/11/23.
 */

public class MesFragment extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener
{
    public static List<Message> messageList;
    private ListView mesListView;
    public static MesListAdapter adapter;
    private SwipeRefreshLayout mes_refresh;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fragment_mes, null);

        initview(view);
        initData();
        bombConnectInit();

        return view;
    }

    private void initData()
    {
        messageList = new ArrayList<>();
        adapter = new MesListAdapter(getContext(), messageList);
        mesListView.setAdapter(adapter);
    }

    private void initview(View view)
    {
        mesListView = (ListView) view.findViewById(R.id.mesListView);
        mesListView.setOnItemClickListener(this);
        mesListView.setOnItemLongClickListener(this);
        mes_refresh = (SwipeRefreshLayout) view.findViewById(R.id.mes_refresh);
        mes_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
        {
            @Override
            public void onRefresh()
            {
                getMessageForServe();
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        Intent intent = new Intent(getActivity(), ChatActivity.class);
        Message message = messageList.get(position);
        intent.putExtra("name", message.getYourname());
        intent.putExtra("FromWhere", 2);
        intent.putExtra("recentmes", message.getRecentMes());
        intent.putExtra("position", position);
        startActivity(intent);
    }
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id)
    {
        //提示用户是否要删除本条消息记录
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle("确定删除本条消息？");
        dialog.setMessage("删除后将无法找回！");
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                deleteMessageFromSevre(position);
            }
        });
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {

            }
        });
        dialog.show();
        return true;
    }

    //从服务器获取消息列表
    private void deleteMessageFromSevre(final int position)
    {
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                Message message = messageList.get(position);
                message.delete(new UpdateListener()
                {
                    @Override
                    public void done(BmobException e)
                    {
                        if (e == null)
                        {
                            messageList.remove(position);
                            adapter.notifyDataSetChanged();
                        }else
                        {
                            L.i("删除Message失败");
                        }
                    }
                });
            }
        }).start();
    }


    //从服务器获取消息列表
    private void getMessageForServe()
    {
        final _User user = BmobUser.getCurrentUser(_User.class);
        //开启新线程来获取消息列表
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                //从服务器上获取消息列表
                BmobQuery<Message> query = new BmobQuery<Message>();
                //返回50条数据，如果不加上这条语句，默认返回10条数据
                query.setLimit(50);
                query.addWhereEqualTo("myname", user.getUsername());
                //执行查询方法
                query.findObjects(new FindListener<Message>()
                {
                    @Override
                    public void done(List<Message> object, BmobException e)
                    {
                        if (e == null)
                        {
                            //Toast.makeText(getActivity(), "查询成功：共"+ object.size() + "条数据。" + i, Toast.LENGTH_SHORT).show();
                            messageList.clear();
                            messageList.addAll(object);
                            Collections.reverse(messageList);
                            getActivity().runOnUiThread(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    adapter.notifyDataSetChanged();
                                    mes_refresh.setRefreshing(false);
                                }
                            });
                        } else
                        {
                            getActivity().runOnUiThread(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    Toast.makeText(getActivity(), "获取失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
            }
        }).start();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        //获取服务器上的聊天列表
        getMessageForServe();
    }

    private void bombConnectInit()
    {
        //TODO 连接：3.1、登录成功、注册成功或处于登录状态重新打开应用后执行连接IM服务器的操作
        _User user = BmobUser.getCurrentUser(_User.class);
        L.i(user.getUsername());
        if (!TextUtils.isEmpty(user.getUsername())) {
            BmobIM.connect(user.getUsername(), new ConnectListener() {
                @Override
                public void done(String uid, BmobException e) {
                    if (e == null) {
                        //连接成功
                        L.i("BmobIM连接成功");
                    } else {
                        //连接失败
                        L.i("BmobIM连接失败");
                    }
                }
            });
        }
    }
}
